package com.movecar.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.adapter.GroupListAdapter;
import com.movecar.dialog.CustomDialog;
import com.movecar.listview.MyListView;
import com.movecar.model.CloudBeansBean;
import com.movecar.model.ClubBean;
import com.movecar.model.GroupBean;
import com.movecar.model.Pictures;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;
import com.movecar.widget.MyGridView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 俱乐部详情
 * 
 * @author Zhao.JQ
 * 
 */
public class ClubDetailActivity extends Activity implements OnClickListener {

	private TextView club_name, club_time, description, owner_phone;
	private ArrayList<Pictures> picturesData = null;
	private MyGridView mGridView;
	private String mSectionId = "";
	private String club_img = "";
	private ImageView clubImg;
	private ScrollView mScrollView;
	private RelativeLayout look_all_relative;
	private ImageLoader imageLoader = null;
	private CustomProgressDialog progressDialog = null;
	private String oldActivityNum;
	private ClubBean mClubBean;
	private MyListView mListView;
	private LinearLayout group_list, main_linear;
	private Button right;
	private CloudBeansBean mCloudBeansBean = null;
	private boolean isClicked = false;
	private int position;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.club_detail);
		position = getIntent().getIntExtra("position", 0);
		initView();
	}

	private void initView() {
		imageLoader = ImageLoader.getInstance();
		// imageLoader.init(Constants.imageLoaderConfiguration(this));
		stopProgressDialog();
		mScrollView = (ScrollView) findViewById(R.id.mScrollView);
		findViewById(R.id.img_layout).setOnClickListener(this);
		// message_board = (Button) findViewById(R.id.message_board);
		Button btn_left = (Button) findViewById(R.id.btn_left);
		btn_left.setVisibility(View.VISIBLE);
		btn_left.setOnClickListener(this);
		right = (Button) findViewById(R.id.btn_right);

		// message_board.setOnClickListener(this);
		main_linear = (LinearLayout) findViewById(R.id.main_linear);
		clubImg = (ImageView) findViewById(R.id.club_img);
		mGridView = (MyGridView) findViewById(R.id.mGridView);
		club_name = (TextView) findViewById(R.id.club_name);
		owner_phone = (TextView) findViewById(R.id.club_owener_phone);
		owner_phone.setOnClickListener(this);
		club_time = (TextView) findViewById(R.id.club_time);
		description = (TextView) findViewById(R.id.description);
		look_all_relative = (RelativeLayout) findViewById(R.id.look_all_relative);
		look_all_relative.setOnClickListener(this);
		mListView = (MyListView) findViewById(R.id.mListView);
		group_list = (LinearLayout) findViewById(R.id.group_list);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("详情");
		if (this.getIntent() != null) {
			mSectionId = getIntent().getStringExtra("sectionId");

			startProgressDialog();
			getClubDetail();

		}
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				if (picturesData != null && picturesData.size() > 0) {
					Intent intent = new Intent(ClubDetailActivity.this, ClubPhotoActivity.class);
					intent.putExtra("Pictures", picturesData);
					intent.putExtra("currentId", arg2);
					startActivity(intent);
				}

			}
		});
	}

	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_left:
			if (isClicked) {
				Intent i = new Intent();
				i.putExtra("position", position);
				setResult(RESULT_OK, i);
			}
			isClicked = false;
			finish();

			break;
		case R.id.img_layout:
			if (picturesData != null && picturesData.size() > 0) {
				Intent intent = new Intent();
				intent.putExtra("Pictures", picturesData);
				startActivity(intent);
			}
			break;

		case R.id.club_owener_phone:
			CustomDialog.Builder customBuilder = new CustomDialog.Builder(ClubDetailActivity.this);
			ImageView img = new ImageView(ClubDetailActivity.this);
			img.setImageResource(R.drawable.ic_launcher);
			customBuilder.setImgIcon(img).setMessage("是否确认打电话?")

			.setPositiveButton("打电话", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent call = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + owner_phone.getText().toString())); // 创建一个意图
					ClubDetailActivity.this.startActivity(call);// 开始意图(及拨打电话)
					dialog.dismiss();

				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					dialog.dismiss();

				}
			});
			customBuilder.create().show();

			break;
		case R.id.look_all_relative:
			Intent next = new Intent(this, GroupActivity.class);
			next.putExtra("sectionId", mSectionId);
			// next.putExtra("club_data", true);
			startActivity(next);
			break;
		case R.id.btn_right:
			isClicked = true;
			startProgressDialog();
			followJsonData(mSectionId);
			getClubDetail();
			break;
		default:
			break;
		}

	}

	@SuppressWarnings("unchecked")
	private void getClubDetail() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "getSectionNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("sectionId", mSectionId));

		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;

				Gson gson = new Gson();
				try {
					mClubBean = gson.fromJson(result, ClubBean.class);
				} catch (Exception e) {
					return;
				}
				club_name.setText("名称：" + mClubBean.getSectionName());
				owner_phone.setText("联系方式：" + mClubBean.getPhone());
				club_time.setText("地址：" + mClubBean.getAddress());
				description.setText(mClubBean.getDescription());
				if ("0".equals(mClubBean.getScreenFlag())) {
					right.setBackgroundResource(R.drawable.club_detail_unfollow);
					right.setVisibility(View.VISIBLE);
					right.setOnClickListener(ClubDetailActivity.this);
				} else {
					right.setBackgroundResource(R.drawable.club_detail_follow);
					right.setVisibility(View.VISIBLE);
					right.setOnClickListener(ClubDetailActivity.this);
				}
				if ("0".equals(mClubBean.getMsgCount())) {
					group_list.setVisibility(View.GONE);

					oldActivityNum = "0";

				} else {
					oldActivityNum = mClubBean.getMsgCount();
					if (!"0".equals(mClubBean.getMsgArr())) {

						Type type = new TypeToken<List<GroupBean>>() {
						}.getType();
						Gson gson1 = new Gson();
						Object fromJson = gson1.fromJson(mClubBean.getMsgArr(), type);
						List<GroupBean> mDataList = null;
						try {
							mDataList = (List<GroupBean>) fromJson;
						} catch (Exception e) {
							return;
						}
						GroupListAdapter adapter = new GroupListAdapter(ClubDetailActivity.this, mDataList);
						mListView.setAdapter(adapter);
					} else {
						look_all_relative.setVisibility(View.GONE);
					}

				}
				picturesData = new ArrayList<Pictures>();
				if ("0".equals(mClubBean.getPicCount())) {
					clubImg.setVisibility(View.VISIBLE);

					imageLoader.displayImage(AppConfig.HOST + mClubBean.getDefaultPic(), clubImg);

				} else {
					try {
						JSONObject jsonObject = null;

						JSONArray jsonArray = new JSONArray(mClubBean.getPicArr());
						picturesData.clear();
						for (int i = 0; i < jsonArray.length(); i++) {
							jsonObject = jsonArray.getJSONObject(i);
							Pictures bean = new Pictures();
							bean.setUrl(jsonObject.getString("pic"));
							picturesData.add(bean);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					DataAdapter adapter = new DataAdapter(ClubDetailActivity.this, picturesData);
					mGridView.setVisibility(View.VISIBLE);
					mGridView.setAdapter(adapter);

				}
				new Handler().post(new Runnable() {
					@Override
					public void run() {
						mScrollView.fullScroll(ScrollView.FOCUS_UP);
						main_linear.setVisibility(View.VISIBLE);
						stopProgressDialog();
					}
				});
			}

			@Override
			public void onFail(String exception) {

				stopProgressDialog();
				Alert.error(ClubDetailActivity.this,"与服务器连接失败，请检查网络");

			}
		}, ClubBean.class, AppConfig.CLUB).execute(params);
	}

	/**
	 * 关注
	 * 
	 * @param sectionId
	 */
	@SuppressWarnings("unchecked")
	private void followJsonData(String sectionId) {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "specialFocusNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("sectionId", sectionId));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mCloudBeansBean = gson.fromJson(result, CloudBeansBean.class);
				} catch (Exception e) {
					return;
				}
				if ("0".equals(mCloudBeansBean.getResultCode())) {

				} else {
					stopProgressDialog();
					Alert.info(ClubDetailActivity.this, result);
				}
			}

			@Override
			public void onFail(String exception) {

				Alert.error(ClubDetailActivity.this,"与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.CLUB).execute(params);
	}

	class DataAdapter extends BaseAdapter {

		Activity activity;
		private LayoutInflater inflater;
		private ViewHolder viewHolder = null;

		ArrayList<Pictures> picturesData;

		DataAdapter(Activity activity, ArrayList<Pictures> picturesData) {

			this.activity = activity;
			this.picturesData = picturesData;
			inflater = LayoutInflater.from(activity);

		}

		@Override
		public int getCount() {

			return picturesData.size();
		}

		@Override
		public Object getItem(int arg0) {

			return picturesData.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {

			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup arg2) {

			if (view == null) {
				viewHolder = new ViewHolder();
				view = inflater.inflate(R.layout.club_img_item, null);

				viewHolder.mImageView = (ImageView) view.findViewById(R.id.mImageView);

				view.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) view.getTag();
			}

			imageLoader
					.displayImage(
							AppConfig.HOST
									+ picturesData.get(position).getUrl()
											.substring(0, picturesData.get(position).getUrl().length() - 4) + "_thumb"
									+ ".jpg", viewHolder.mImageView);

			return view;
		}

		class ViewHolder {

			ImageView mImageView;
		}
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	public boolean dispatchKeyEvent(KeyEvent event) {

		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getRepeatCount() == 0) {

			if (isClicked) {
				Intent i = new Intent();
				i.putExtra("position", position);
				setResult(RESULT_OK, i);
			}
			isClicked = false;
			finish();
			return false;
		} else {
			return super.dispatchKeyEvent(event);
		}
	}
}
